import * as api from '../../api/common';

Page({
  data: {
    showVerification: false,
    phoneNumber: '',
    verificationCode: '',
    password: '',
    confirmPassword: '',
    countdown: 0,
    timer: null,
    checked: false,
    loading: false
  },

  onLoad(options) {
    // 页面加载时的初始化工作，如果有需要可以在这里处理
  },

  onUnload() {
    // 页面卸载时清除定时器，避免内存泄漏
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 去登录页面
  loginByAccount() {
    tt.redirectTo({
      url: '../loginByAccount/index'
    });
  },

  // 输入手机号
  inputPhone(e) {
    this.setData({
      phoneNumber: e.detail.value
    });
  },

  // 输入验证码
  inputVerificationCode(e) {
    this.setData({
      verificationCode: e.detail.value
    });
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 输入确认密码
  inputConfirmPassword(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  // 校验手机号格式
  checkPhoneNumber() {
    const phoneNumber = this.data.phoneNumber.trim();
    const reg = /^1\d{10}$/;
    return reg.test(phoneNumber);
  },

  // 发送验证码
  async sendVerificationCode() {
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })
    const phoneNumber = this.data.phoneNumber.trim();
    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    try {
      const response = await api.sendVerificationCode({
        phone: phoneNumber
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });
      } else {
        tt.showToast({
          title: '验证码发送成功',
          icon: 'success'
        });

        this.setData({
          showVerification: true
        });

        this.startCountdown();
      }
    } catch (error) {
      tt.showToast({
        title: '验证码发送失败，请重试',
        icon: 'none'
      });
      console.error('Failed to send verification code:', error);
    } finally {
      setTimeout(() => {
        this.setData({
          loading: false
        })
      }, 500)
    }
  },
  // 开始倒计时
  startCountdown() {
    let count = 60;
    this.setData({
      countdown: count
    });

    this.data.timer = setInterval(() => {
      count--;
      if (count >= 0) {
        this.setData({
          countdown: count
        });
      } else {
        clearInterval(this.data.timer);
        this.setData({
          countdown: 0
        });
      }
    }, 1000);
  },

  // 勾选
  toggleCheckbox() {
    this.setData({
      checked: !this.data.checked // 切换勾选状态
    });
  },
  gotoPrivacyPage() {
    tt.navigateTo({
      url: 'pages/privacy/index'
    });
  },

  gotoServicePage() {
    tt.navigateTo({
      url: 'pages/service/index'
    });
  },
  // 重置密码
  async resetPassword() {
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })

    const phoneNumber = this.data.phoneNumber.trim();
    const verificationCode = this.data.verificationCode.trim();
    const password = this.data.password.trim();
    const confirmPassword = this.data.confirmPassword.trim();

    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (!verificationCode) {
      tt.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (password.length < 6) {
      tt.showToast({
        title: '密码长度至少为6位',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (password !== confirmPassword) {
      tt.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (!this.data.checked) {
      tt.showToast({
        title: '请阅读并同意用户协议和隐私权条款',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }
    try {
      const response = await api.resetPassword({
        phone: phoneNumber,
        code: verificationCode,
        password: password
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });

      } else {
        tt.showToast({
          title: '密码重置成功',
          icon: 'success'
        });

        // 清除缓存信息
        tt.removeStorageSync('info');

        // 密码重置成功后的操作，例如跳转到登录页面
        tt.navigateTo({
          url: '../loginByAccount/index'
        });
      }
    } catch (error) {
      tt.showToast({
        title: error,
        icon: 'none'
      });
    } finally {
      setTimeout(() => {
        this.setData({
          loading: false
        })
      }, 500)
    }
  }
});